package com.petecat.interchan;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.search.MultiMatchQuery.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.petecat.interchan.base.project.entity.EsServer;
import com.petecat.interchan.base.project.entity.EsServerHistory;
import com.petecat.interchan.base.project.entity.HardWareDisk;
import com.petecat.interchan.base.project.service.IProjectService;
import com.petecat.interchan.base.util.ExeclOutFile;
import com.petecat.interchan.es.EsDaoInter;
import com.petecat.interchan.protocol.data.PageVO;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EsQueryServerInfo {
	
	@Autowired
	private EsDaoInter esDao;
	
	@Autowired
	private IProjectService projectService;
	
	private String token;
	
	private String mac;
	@Before
	public void before() {
		token = "953168716228956160";
		mac = "7c:67:a2:7d:0b:99";
	}
	
	/**
	 * 通过Token查询项目所在的服务器ES信息
	 */
	@Test
	public void getProjectServer() {
		List<EsServer> queryServerInfo = projectService.queryServerInfo(token);
		queryServerInfo.forEach(info->System.out.println(info.toString()));
	}
	
	/**
	 * 查询所有的项目服务器ES信息
	 */
	@Test
	public void queryAllServerInfo() {
		List<EsServer> list = new ArrayList<>();
		TransportClient client = null;
		EsServer esServer = null;
		HardWareDisk disk = null;
		String statusText = "";
		JSONArray head = null;
		JSONArray body = null;
		String sourceAsString = "";
		List<JSONArray> jsonList = new ArrayList<>();
		try {
			client = esDao.getClient();
			SearchResponse response = client.prepareSearch("monitor-server-status-common")
											.execute().get();
			SearchHits hits = response.getHits();
			if (hits.totalHits > 0) {
				//只需要一个head
				head = new JSONArray();
				head.add("服务器名称");
				head.add("系统版本");
				head.add("服务器状态");
				head.add("总运行时长");
				head.add("内存大小");
				head.add("CPU总个数");
				head.add("CPU物理个数");
				head.add("磁盘总数量");
				for (SearchHit hit : hits.getHits()) {
					body = new JSONArray();
					sourceAsString = hit.getSourceAsString();
					esServer = JSON.parseObject(sourceAsString, EsServer.class);
					Long runTime = null;
					if(esServer.getStopTime() != null) {
						runTime = Long.parseLong(esServer.getStopTime()) - Long.parseLong(esServer.getSendTime());
					}else {
						runTime = new Date().getTime() - Long.parseLong(esServer.getSendTime());
					}
					//String stampToDate = stampToDate(runTime.toString(),null);
					esServer.setRunTime("2017-8-02");
					TermQueryBuilder tokenQuery = QueryBuilders.termQuery("header.token", esServer.getToken());
					MatchQueryBuilder macQuery = QueryBuilders.matchQuery("header.mac", esServer.getMac());
					BoolQueryBuilder must = QueryBuilders.boolQuery().must(tokenQuery).must(macQuery);
					SearchResponse serverRep = client.prepareSearch("monitor-server-info")
							.addSort("body.sendTime", SortOrder.DESC).setQuery(must).setSize(1).execute().get();
					SearchHits serverHits = serverRep.getHits();
					if (serverHits.totalHits > 0) {
						for (SearchHit hit1 : serverHits.getHits()) {
							sourceAsString = hit1.getSourceAsString();
							JSONObject bodyJson = JSON.parseObject(sourceAsString).getJSONObject("body");
							JSONObject cpuJson = bodyJson.getJSONObject("cpu");
							esServer.setCpuLogicalCount(cpuJson.getString("logicalCount"));
							esServer.setCpuTotalCount(cpuJson.getString("total"));
							esServer.setPlatform(bodyJson.getString("platform"));
							esServer.setSystem(bodyJson.getString("system"));
							JSONObject memoryJson = bodyJson.getJSONObject("virtual_memory");
							esServer.setMemTotal(memoryJson.getString("total"));
							JSONObject diskJson = bodyJson.getJSONObject("disks");
							List<HardWareDisk> diskList = new ArrayList<>();
							JSONObject diskObject = null;
							//写入excel
							body.add(esServer.getHostname());
							body.add(bodyJson.getString("platform"));
							if("1".equals(esServer.getStatus())) {
								statusText = "服务器正在运行";
							}else {
								statusText = "服务器已经停止";
							}
							body.add(statusText);
							body.add(esServer.getRunTime());
							body.add(memoryJson.getString("total"));
							body.add(cpuJson.getString("total"));
							body.add(cpuJson.getString("logicalCount"));
							body.add(diskList.size());
							for(Map.Entry<String,Object> map : diskJson.entrySet()) {
							    diskObject = JSONObject.parseObject(map.getValue().toString());
								disk = new HardWareDisk();
								head.add(map.getKey()+"磁盘容量");
								head.add(map.getKey()+"磁盘类型");
								body.add(diskObject.getString("total"));
								body.add(diskObject.getString("fstype"));
								disk.setDevice(map.getKey());
								disk.setTotal(diskObject.getString("total"));
								disk.setFstype(diskObject.getString("fstype"));
								diskList.add(disk);
							}
							esServer.setDiskList(diskList);
							esServer.setDiskCount(diskList.size());
						}
					}
					list.add(esServer);
					jsonList.add(body);
				}
				//String queryServerName = this.queryServerName(esServer.getToken());
				//创建文件 
//				HSSFWorkbook book = ExeclOutFile.expExcel(head, jsonList, "互联网渠道");
//				ExeclOutFile.outFile(book, "C:\\Users\\王来利\\Desktop\\任务\\1.xls");
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} finally {
			if (client != null) {
				esDao.resume(client);
			}
		}
		/*return projectService.queryAllServerInfo();*/
	}
	
	/**
	 * 通过Token查询项目服务器的总数量和开机数量
	 */
	@Test
	public void getProjectServerTotal() throws InterruptedException {
		TransportClient client = null;
		try {
			client = esDao.getClient();
			TermQueryBuilder tokenTermQuery = QueryBuilders.termQuery("token", token);
			TermQueryBuilder statusTermQuery = QueryBuilders.termQuery("status", "0");
			BoolQueryBuilder must = QueryBuilders.boolQuery().must(statusTermQuery).must(tokenTermQuery);
			//查询所有的
			SearchResponse actionGet = client.prepareSearch("monitor-server-status-common").setSize(100).setQuery(tokenTermQuery).execute().actionGet();
			SearchHits hits = actionGet.getHits();
			Integer serverTotal = hits.getHits().length;
			//查询在线的
			SearchResponse usedServer = client.prepareSearch("monitor-server-status-common").setSize(100).setQuery(must).execute().actionGet();
			SearchHits usedHhits = usedServer.getHits();
			Integer usedCount = usedHhits.getHits().length;
			System.out.println("总"+serverTotal+"在线"+usedCount);
		} finally {
			if (client != null) {
				esDao.resume(client);
			}
		}
		
	}
	
	/**
	 * 通过MAC地址查询历史服务器信息ES接口
	 * @Title: getProjectHistoryByMac   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param:       
	 * @return: void      
	 * @throws
	 */
	@Test
	public void getProjectHistoryByMac() {
		PageVO<EsServerHistory> vo = new PageVO<>();
		TransportClient client = null;
		String sourceString = "";
		EsServerHistory history = null;
		List<EsServerHistory> serverInfoList = new ArrayList<>();
		try {
			client = esDao.getClient();
			TermQueryBuilder macTermQuery = QueryBuilders.termQuery("mac", mac);
			//查询所有的
			SearchResponse actionGet = client.prepareSearch("monitor-server-status")
											 .setSize(1000)
											 .setQuery(macTermQuery)
											 .execute()
											 .actionGet();
			SearchHits hits = actionGet.getHits();
			if(hits.getHits().length > 0) {
				for (SearchHit searchHit : hits) {
					sourceString = searchHit.getSourceAsString();
					history = JSONObject.parseObject(sourceString,EsServerHistory.class);
					serverInfoList.add(history);
				}
			}
		} finally {
			if (client != null) {
				esDao.resume(client);
			}
		}
		vo.setTotalSize(serverInfoList.size());
		vo.setResult(serverInfoList);
	}
	
}
